package com.pro.xwt.file.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.pro.xwt.common.model.BEmployee;
import com.pro.xwt.common.model.DFile;
import com.pro.xwt.common.service.DFileService;
import com.pro.xwt.common.service.DFolderService;
import com.pro.xwt.common.utils.Common;
import com.pro.xwt.common.utils.FileUtils;
import com.pro.xwt.rest.ResponseResult;
@Controller
@RequestMapping("/files")
public class FilesController {
	
	@Autowired
	DFileService dFlieService;
	@Autowired
	DFolderService dFolderService;
	
	//上传文件操作
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
	public ResponseResult upload(@RequestParam(value = "file", required = false)MultipartFile file,HttpServletRequest request){
		DFile fileInfo = new DFile();
		BEmployee emp = null;
		System.out.println(request.getAttribute("user"));
		if (request.getAttribute("user")==null||request.getAttribute("user").equals("")||request.getAttribute("user").equals(" ")) {
              return ResponseResult.success("当前操作用户不能为空",fileInfo);
  		}else{
  			emp = ((BEmployee)request.getAttribute("user"));
  		}
		 if (file == null){
			 return ResponseResult.success("上传文件为空",fileInfo);
		 }else{
		
		String uploadPath = Common.FILE_SAVE_BASEPATH; //上传路径
        String directoryId = request.getParameter("directoryId");
        String projId = request.getParameter("projId");
        String lastFileName = file.getOriginalFilename();
        Long size = (long) 0;
        
        //查询是否同文件夹下已存在该文件
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("name", file.getOriginalFilename());
        map.put("projId", projId);
        map.put("folderId", directoryId);
        if (dFlieService.findByCondition(map)!=null) {
        	  return ResponseResult.fail("该文件夹已存在同名文件",fileInfo);
		}
      
        //取得当前上传文件的扩展名
        String ExtensionName = lastFileName.substring(lastFileName.lastIndexOf(".")==0?0:lastFileName.lastIndexOf("."));
        String UUID = Common.generateUUID();
        File tempFileDir = new File(uploadPath);
        if (!tempFileDir.exists()) {
            tempFileDir.mkdirs();
        }
        System.out.println("开始");  
        System.out.println(uploadPath);  
        File targetFile = new File(uploadPath, UUID+ExtensionName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        //保存  
        try {  
            file.transferTo(targetFile);  
            size = targetFile.length();
            System.out.println(size);
        } catch (Exception e) {  
            e.printStackTrace();  
            return ResponseResult.fail("保存文件时出错", fileInfo);
        }
        if ("undefined".equals(directoryId)) {
        	directoryId=null;
		}else{
			dFolderService.updateTime(new Date(),directoryId);
		}
        //更新数据库
        fileInfo.setId(UUID);
        fileInfo.setName(lastFileName);
        fileInfo.setFolderId(directoryId);
        fileInfo.setStoragePath(UUID+ExtensionName);
        fileInfo.setSize(size);
        fileInfo.setDeleteState("0");
        fileInfo.setUploadTime(new Date());
        fileInfo.setUploadEmpId(emp.getId());
        fileInfo.setUploadEmpName(emp.getName());;
        fileInfo.setProjId(projId);
        dFlieService.upload(fileInfo);
        dFolderService.updateSize(size,directoryId);
        return ResponseResult.success("保存文件时成功", fileInfo); 
		}
	}
	
	//断点上传文件操作
    @RequestMapping(value = "/file/upload/26+59+561561", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult uploadPart(HttpServletRequest request){
        String uploadPath = Common.FILE_SAVE_BASEPATH; //上传路径
        String id = request.getParameter("id");                 //文件的id  之后用于临时目录
        String directoryId = request.getParameter("directoryId");
        String projId = request.getParameter("projId");
        Long size = (long) 0;
        //查询是否同文件夹下已存在该文件
        Map<String,Object> map = new HashMap<String,Object>();
        if (dFlieService.findByCondition(map)==null) {
        	  return ResponseResult.success("该文件夹已存在同名文件",false);
		}
        
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
        // 如果大于1说明是分片处理
        int chunks = 1;
        int chunk = 0;
        //取得request中的所有文件名
        Iterator<String> iterator = multiRequest.getFileNames();
        if(multiRequest.getParameter("chunks") != null){
            chunks = Integer.parseInt(multiRequest.getParameter("chunks"));
            chunk = Integer.parseInt(multiRequest.getParameter("chunk"));
        }
        try {
            while(iterator.hasNext()) {
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iterator.next());
                if (file != null) {
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //取得当前上传文件的扩展名
                    String ExtensionName = myFileName.substring(myFileName.lastIndexOf(".")==0?0:myFileName.lastIndexOf("."));
                    // 临时目录用来存放所有分片文件
                    String tempFileDirStr = uploadPath + "/" + id;
                    File tempFileDir = new File(tempFileDirStr);
                    if (!tempFileDir.exists()) {
                        tempFileDir.mkdirs();
                    }
                    // 分片处理时，前台会多次调用上传接口，每次都会上传文件的一部分到后台(默认每片为5M)
                    File tempPartFile = new File(tempFileDir, myFileName + "_" + chunk + ".part");
                    FileUtils.copyInputStreamToFile(file, tempPartFile);
                    // 是否全部上传完成
                    // 所有分片都存在才说明整个文件上传完成
                    boolean uploadDone = true;
                    for (int i = 0; i < chunks; i++) {
                        File partFile = new File(tempFileDir, myFileName + "_" + i + ".part");
                        if (!partFile.exists()) {
                            uploadDone = false;
                        }
                    }
                    // 所有分片文件都上传完成
                    // 将所有分片文件合并到一个文件中  得到 destTempFile 就是最终的文件  然后保存即可
                    String UUID = Common.generateUUID()+ExtensionName;
                    if (uploadDone) {
                        File destTempFile = new File(uploadPath, UUID);
                        for (int i = 0; i < chunks; i++) {
                            File partFile = new File(tempFileDir, myFileName + "_" + i + ".part");
                            //合并分片文件
                            FileUtils.copyFile(partFile, destTempFile);
                            size = partFile.length();
                        }
                        //删除临时文件夹 以及里面的文件
                        FileUtils.deleteDirectory(tempFileDir);
                        //更新数据库
                        DFile fileInfo = new DFile();
                        fileInfo.setId(UUID);
                        fileInfo.setName(myFileName);
                        fileInfo.setFolderId(directoryId);
                        fileInfo.setStoragePath(uploadPath);
                        fileInfo.setSize(size);
                        fileInfo.setProjId(projId);
                        if (request.getAttribute("user")==null||request.getAttribute("user").equals("")||request.getAttribute("user").equals(" ")) {
                        	 FileUtils.deleteDirectory(tempFileDir);
                             return ResponseResult.success("当前操作用户不能为空",false);
						}else{
                        String empId = ((BEmployee)request.getAttribute("user")).getId();
                        	fileInfo.setUploadEmpId(empId);
						}
                        
                        dFlieService.upload(fileInfo);
                    } else {
                        // 临时文件创建失败  删除临时文件夹 以及里面的文件
                        if (chunk == chunks -1) {
                            FileUtils.deleteDirectory(tempFileDir);
                            return ResponseResult.success("上传文件失败",false);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseResult.success("上传文件成功",true);
    }
}
